<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" prop="id" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="文章标题" align="center">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>

      <el-table-column label="文章分类" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cate_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" class-name="status-col">
        <template slot-scope="{row}">
          {{ row.create_time|formatDate}}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" class-name="status-col">
        <template slot-scope="{row}">
          {{ row.update_time|formatDate}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-button size="mini" type="danger" @click="deleteOperation(row.id)">
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]">

      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 80%; margin-left:70px;">
         <el-form-item label="文章标题" prop="title">
          <el-input v-model="temp.title" type="text" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
         <el-select v-model="temp.cate_id" placeholder="请选择分类" class="filter-item">
           <el-option v-for="(item,index) in this.cate_list" :label="item.name" :value="item.id"
             :key="index" />
         </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content" >
           <el-input type="textarea" v-model="temp.content" :rows="10"></el-input>
        </el-form-item>


      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  var check_total_money = (rule, value, callback) => {
    if (value === '') {
      callback(new Error('请再次输入密码'));
    } else if (value <= 0) {
      callback(new Error('必须大于0!'));
    } else {
      callback();
    }
  };
  import {
    create,
    update,
    deleteRecord,
    getCategoryList,
    getAllList
  } from '@/api/article'
  import {
    formatDate
  } from '@/utils/formatDate.js'
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'BalanceTable',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      formatDate(time) {
        time = time * 1000
        let date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    data() {
      return {
        tableKey: 0,
        tableRecord: 1,
        list: [],
        total: 0,
        listLoading: true,
        dialogStatus: '',
        dialogFormVisible: false,
        listQuery: {
          page: 1,
          limit: 20
        },
        temp: {
          title: null,
          cate_id:null,
          content:null
        },
        cate_list:[],
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        rules: {
          title: [{
            required: true,
            message: '文章标题必须填写',
            trigger: 'blur'
          }],
          cate_id: [{
            required: true,
            message: '文章必须选择',
            trigger: 'onchange'
          }],
          content: [{
            required: true,
            message: '文章内容必须填写',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.listLoading = false
      this.getList()
    },
    methods: {
      deleteOperation(id) {
        deleteRecord(id).then(res => {
          this.$notify({
            title: 'Success',
            message: 'Created Successfully',
            type: 'success',
            duration: 2000,
            onClose: this.getList()
          })
 this.$refs['dataForm'].resetFields();
        })
      },
      handleCreate() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        getCategoryList().then(resp=>{
          this.cate_list=resp.data
        })
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            create(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000,
                onClose: this.getList()
              })
               this.$refs['dataForm'].resetFields();
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        getCategoryList().then(resp=>{
          this.cate_list=resp.data
        })
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)

            update(tempData).then(() => {

              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000,
                onClose: this.getList()
              })
            })
          }
        })
      },
      getList() {
        this.listLoading = true
        getAllList(this.listQuery).then(response => {
          this.list = response.data.list
          this.total = response.data.count
          setTimeout(() => {
            this.listLoading = false
          }, 1.0 * 1000)
        })
      }
    }
  }
</script>

<style>
</style>
